import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Form, Button } from 'antd'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'

import ChangeScoreModal from './com/changeScoreModal'
import { widgetType } from 'constants'

import PropTypes from 'prop-types'

import Style from './manage.css'

class manage extends Component {
  static propTypes = {
    scoreData: PropTypes.object,
    getScoreList: PropTypes.func,
    setInteralDetail: PropTypes.func,
    updateScore: PropTypes.func,
    scoreDataLoading: PropTypes.bool,
    router: PropTypes.object,
    form: PropTypes.object
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      selectedRowKeys: [],
      showChangeScoreModal: false
    }
    this.onPageChange = this.onPageChange.bind(this)
  }

  componentDidMount () {
    this.init()
  }

  init = (values = {}) => {
    const { pageNo, pageSize } = this.state
    this.props.getScoreList({
      pageNo,
      pageSize,
      ...values
    })
  }

  search = (values = {}) => {
    if (values === 'custom') {
      const { form } = this.props
      form.validateFields((err, items) => {
        if (!err) {
          values = items
        }
      })
    }
    this.init(values)
  }

  onPageChange (pageNo, pageSize) {
    const params = {}
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getScoreList(params)
  }

  reset = (custom) => {
    if (custom === 'custom') {
      const { form } = this.props
      form.resetFields()
    }
    this.setState({
      pageNo: 1,
      pageSize: 20
    })
    this.init()
  }

  getFilterCols = () => {
    return [
      {
        label: '输入搜索',
        id: 'searchField',
        widget: widgetType.input,
        placeholder: '请输入用户手机号/用户名称',
        span: 8
      }, {
        label: '用户类型',
        id: 'memberLevel',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [
          {
            text: '普通会员',
            value: 'NORMAL_LEVEL'
          },
          {
            text: '尊贵会员',
            value: 'PAY_LEVEL'
          }
        ],
        span: 8
      },
      {
        label: false,
        key: 'custom',
        widget: 'custom',
        render: () => {
          return (
            <>
              <Button type='primary' style={{ marginRight: 16 }} onClick={() => this.search('custom')}>查询</Button>
              <Button onClick={() => this.reset('custom')}>重置</Button>
            </>
          )
        },
        span: 6
      }
    ]
  }

  getTableCols = () => {
    return [
      {
        title: '用户ID',
        dataIndex: 'userId'
      },
      {
        title: '用户手机号',
        dataIndex: 'mobile'
      },
      {
        title: '用户名称',
        dataIndex: 'userName'
      },
      {
        title: '用户类型',
        dataIndex: 'memberLevelName'
      },
      {
        title: '可用积分',
        dataIndex: 'residueIntegration'
      },
      {
        title: '历史积分',
        dataIndex: 'totalIntegration'
      },
      {
        title: '操作',
        width: 250,
        dataIndex: 'operate',
        key: 'operate',
        render: (text, record) => {
          return <>
            <a className={Style['a-btn']} onClick={() => this.handleShowDetail(record)} >积分明细</a>
            {/* <Authorized auth='USERS:SCORE:EDIT'>
              <a className={Style['a-btn']} onClick={() => this.handleChangeScore(record)}>修改数值</a>
            </Authorized> */}
          </>
        }
      }
    ]
  }

  handleShowDetail = record => {
    const { userId } = record
    this.props.router.push(`/users/integral/detail/${userId}`)
  }

  handleChangeScore = record => {
    this.setState({
      currentRow: record,
      showChangeScoreModal: true
    })
  }

  confirmChangeScore = values => {
    // FIXME 调用接口 没有反应
    const { currentRow } = this.state
    this.props.updateScore({
      userId: currentRow.userId,
      ...values
    }).then(() => {
      this.setState({
        showChangeScoreModal: false
      })
      this.init()
    })
  }

  handleToScoreRule = () => {
    this.props.router.push('/users/integral/rules')
  }

  render () {
    const { selectedRowKeys, pageNo, pageSize, showChangeScoreModal } = this.state
    const { form, scoreData, scoreDataLoading } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: scoreData && scoreData.total,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange
    }
    return (
      <>
        <ContentBox>
          <Filters
            cols={this.getFilterCols()}
            form={form}
            search={this.search}
            reset={this.reset}
            actions={false}
          >
            {/* <Button type='primary' onClick={this.handleToScoreRule}>积分规则</Button> */}
          </Filters>
          <CustomTable
            selectedRowKeys={selectedRowKeys}
            multipleSelect={this.onSelectChange}
            multiple
            loading={scoreDataLoading}
            columns={this.getTableCols()}
            dataSource={(scoreData && scoreData.list) || []}
            pagination={pagination}
          />
          <ChangeScoreModal
            visible={showChangeScoreModal}
            onOk={this.confirmChangeScore}
            onCancel={() => this.setState({ showChangeScoreModal: false })}
          />
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  scoreData: state.users.scoreData,
  scoreDataLoading: state.loading.effects.users.getScoreList
})
const mapDispatch = dispatch => ({
  login: dispatch.common.createLogin,
  getScoreList: dispatch.users.getScoreList,
  setInteralDetail: dispatch.users.setInteralDetail,
  updateScore: dispatch.users.updateScore
})

const manageForm = Form.create()(manage)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(manageForm)
)
